package com.cloudfun.campusshare.common.interceptor;

import com.cloudfun.campusshare.common.constant.BaseConstant;
import com.cloudfun.campusshare.common.constant.TokenType;
import com.cloudfun.campusshare.common.model.AccessToken;
import com.cloudfun.campusshare.common.model.Token;
import com.cloudfun.campusshare.common.security.AuthRequired;
import com.cloudfun.campusshare.service.TokenFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * Created by linyangping on 2019/11/6.
 */
//@Slf4j
//@Component
//@Order(3)
public class RequestTokenArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private TokenFactory tokenFactory;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return (parameter.getParameterType().isAssignableFrom(Token.class) || parameter.getParameterType().isAssignableFrom(AccessToken.class))
                && parameter.hasParameterAnnotation(AuthRequired.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        AuthRequired authRequired = parameter.getParameterAnnotation(AuthRequired.class);

        if (authRequired.type().getCode() == TokenType.TOOLKIT.getCode()) {
            String accessStr = webRequest.getHeader(BaseConstant.T_ACCESS_TOKEN);
            AccessToken accessToken = tokenFactory.verifyAccessStr(accessStr);
            return accessToken;
        } else {
            String jwtStr = webRequest.getHeader(BaseConstant.X_ACCESS_TOKEN);
            Token token = tokenFactory.verifyJwt(jwtStr);
            return token;
        }

    }
}

